import {
    ATTR, TEXT,REPLACE,REMOVE
} from './patchType'
import { setAttrs,render } from './virtualDom';

import Element from './Element'
let finalPatches = {};
let rnIndex = 0;

function doPatch(rDom,patches){
    finalPatches = patches;
    rNodeWalk(rDom);
}

function rNodeWalk(rNode){

    const rnPatch = finalPatches[rnIndex++];

    if(rnPatch){
        patchAction(rNode,rnPatch) 
    }
    let childNodes = rNode.childNodes;
        [...childNodes].map((c)=>{
            rNodeWalk(c);
        })
}


function patchAction(rNode,rnPatch ){
    rnPatch.map((p)=>{
        console.log(p)
        switch (p.type) {
            case ATTR:
                for(let key in p.attrs){
                    let value = p.attrs[key];
                    if(value){
                        setAttrs(rNode,key,value);
                    }else{
                        rNode.removeAttribute(key);
                    }
                }
            break;
            case TEXT:
                rNode.textContent = p.text;
            break;
            case  REPLACE:
                console.log(p.newNode)
                const newNode = (p.newNode instanceof Element)?
                render(p.newNode):document.createTextNode(p.newNode)
                rNode.parentNode.replaceChild(newNode,rNode)

            break;
            case REMOVE:
                rNode.parentNode.removeChild(rNode)
            break; 
            default:
            break;
        }
    })
}


export default doPatch;